package com.google.code.sip.ucenter.ws.resources;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.core.UriInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.sip.ucenter.converter.ConverterUtils;

public abstract class AbstractResource {
	private static final Logger logger = LoggerFactory
			.getLogger(AbstractResource.class);
	@Context
	protected UriInfo uri;

	@Context
	protected ServletContext context;

	@Context
	protected SecurityContext security;

	@Context
	protected HttpServletRequest request;

	@Context
	protected HttpServletResponse response;

	static {
		ConverterUtils.registConverter();
	}

	/**
	 * @param content
	 * @return
	 */
	protected StreamingOutput getStreamingOutput(final Object content) {
		return new StreamingOutput() {
			@Override
			public void write(OutputStream out) throws IOException,
					WebApplicationException {
				PrintWriter writer = new PrintWriter(out);
				writer.println(content);
				writer.close();
			}
		};
	}

	protected void printErrorMsg(Throwable e, Object bizInfo) {
		logger.error("发生运行时异常:" + bizInfo, e);
		StackTraceElement[] stackTraceElements = e.getStackTrace();
		if (stackTraceElements != null && stackTraceElements.length > 0) {
			for (StackTraceElement stackTraceElement : stackTraceElements) {
				logger
						.error("exeption file:"
								+ stackTraceElement.getFileName());
				logger.error("exeption class:"
						+ stackTraceElement.getClassName());
				logger.error("exeption method:"
						+ stackTraceElement.getMethodName());
				logger.error("exeption line:"
						+ stackTraceElement.getLineNumber());
			}
		}
		logger.error("异常原因:" + e.getCause());
		logger.error("异常StackTrace:" + e.getStackTrace());
		e.printStackTrace();
	}
}
